from file2h import file2h
import sys, os, re


def get_used_icon(json_file):
    print(json_file)
    fp = open(json_file, 'r', encoding='utf-8')
    data = fp.readlines()
    fp.close()
    icon_used = re.findall('icon_file_name_.+?".+?"(.+?.png)"', str(data))
    return icon_used


def dir2h(dir_in, dir_out=None):
    dir_out = dir_out if dir_out else "%s_c" % (dir_in[:-1] if dir_in.endswith('/') else dir_in)
    os.makedirs(dir_out, exist_ok=True)
    file_list = os.listdir(dir_in)
    icon_list = [x for x in file_list if x.endswith('.png')]
    json_list = [x for x in file_list if x.endswith('.json')]
    if not json_list:
        print('Without json file!')
        return
    if len(json_list) != 1:
        print("More json files exist!")
        return
    icon_used = get_used_icon(os.path.join(dir_in, json_list[0]))
    icon_used = list(set(icon_used))
    for icon in icon_used:
        if icon not in icon_list:
            print('%s not in %s' %(icon, dir_in))
            return
    json_h = file2h(os.path.join(dir_in, json_list[0]), dir_out)
    icon_h = [file2h(os.path.join(dir_in, icon), dir_out) for icon in icon_used]
    fp = open('./file_binary_array_list_en.c', 'w')
    fp.write('#include "file_binary_array_list_en.h"\n\n')
    fp.write('#include "%s/%s"\n' %(dir_out, json_h))
    for icon in icon_h:
        fp.write('#include "%s/%s"\n' %(dir_out, icon))
    fp.write('\n\n')
    fp.write('static T_DjiWidgetFileBinaryArray s_EnWidgetFileBinaryArrayList[] = {\n')
    fp.write('\t{%s_fileName, %s_fileSize, %s_fileBinaryArray}' % (json_h[:-2], json_h[:-2], json_h[:-2]))
    for icon in icon_h:
        fp.write(',\n\t{%s_fileName, %s_fileSize, %s_fileBinaryArray}' % (icon[:-2], icon[:-2], icon[:-2]))
    fp.write('\n};\n\n')
    fp.write('uint32_t g_EnBinaryArrayCount = sizeof(s_EnWidgetFileBinaryArrayList) / sizeof(T_DjiWidgetFileBinaryArray);\n')
    fp.write('T_DjiWidgetFileBinaryArray * g_EnFileBinaryArrayList = s_EnWidgetFileBinaryArrayList;\n')
    fp.write('\n/***************** Create by dir2h *****************/\n')
    print('Done <file_binary_array_list_en.c>')


if __name__ == '__main__':
    if len(sys.argv)<2:
        print('Please input dir of widget\n')
    else:
        dir2h(sys.argv[1], sys.argv[2] if len(sys.argv)>2 else None)